// src/services/person.service.js (FRONTEND)
import axios from 'axios';

const API_URL = 'http://localhost:3000/api';

const apiClient = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// Generic error handler
const handleError = (error, context) => {
    console.error(`[API Error] ${context}:`, error);
    if (error.response) {
        console.error(`> Status: ${error.response.status}`);
        console.error(`> Data:`, error.response.data);
    }
    throw error;
}

// Get all persons
export const getPersons = async () => {
  try {
    const response = await apiClient.get('/persons');
    return response.data;
  } catch (error) {
    handleError(error, 'getPersons');
  }
};

// Get person details by ID
export const getPersonById = async (id) => {
    try {
        const response = await apiClient.get(`/persons/${id}`);
        return response.data;
    } catch (error) {
        handleError(error, `getPersonById(${id})`);
    }
}

// Add a new person
export const createPerson = async (personData) => {
  try {
    const response = await apiClient.post('/persons', personData);
    return response.data;
  } catch (error) {
    handleError(error, 'createPerson');
  }
};

// Update a person
export const updatePerson = async (id, personData) => {
  try {
    const response = await apiClient.put(`/persons/${id}`, personData);
    return response.data;
  } catch (error) {
    handleError(error, `updatePerson(${id})`);
  }
};

// Delete a person
export const deletePerson = async (id) => {
  try {
    const response = await apiClient.delete(`/persons/${id}`);
    return response.data;
  } catch (error) {
    handleError(error, `deletePerson(${id})`);
  }
};

// 获取人员详情
export const getPersonDetail = async (id) => {
  try {
    const response = await fetch(`${API_URL}/persons/${id}`);
    if (!response.ok) {
      throw new Error('获取人员详情失败');
    }
    return await response.json();
  } catch (error) {
    console.error('获取人员详情失败:', error);
    throw error;
  }
}

// 更新人员照片
export const updatePersonPhotos = async (id, photos) => {
  try {
    const response = await fetch(`${API_URL}/persons/${id}/photos`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ photos })
    });
    
    if (!response.ok) {
      throw new Error('更新照片失败');
    }
    
    return await response.json();
  } catch (error) {
    console.error('更新照片失败:', error);
    throw error;
  }
}

// 获取亲属分组
export const getRelatives = async (id) => {
  try {
    const response = await apiClient.get(`/persons/${id}/relatives`);
    return response.data;
  } catch (error) {
    handleError(error, `getRelatives(${id})`);
  }
};

// 获取已删除成员（回收站）
export const getDeletedPersons = async () => {
  try {
    const response = await apiClient.get('/persons/deleted');
    return response.data;
  } catch (error) {
    handleError(error, 'getDeletedPersons');
  }
};

// 恢复已删除成员
export const restorePerson = async (id) => {
  try {
    const response = await apiClient.post(`/persons/${id}/restore`);
    return response.data;
  } catch (error) {
    handleError(error, `restorePerson(${id})`);
  }
};

export const personService = {
  getPersons,
  getPersonById,
  createPerson,
  updatePerson,
  deletePerson,
  getPersonDetail,
  updatePersonPhotos,
  getRelatives,
  getDeletedPersons,
  restorePerson
};

export default personService; 